package com.example.ricebibackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ricebibackend.common.errorcode.ServiceErrorCodeConstants;
import com.example.ricebibackend.common.exception.ServiceException;
import com.example.ricebibackend.controller.param.ChartShowParam;
import com.example.ricebibackend.dao.dataobject.ChartDO;
import com.example.ricebibackend.dao.mapper.ChartMapper;
import com.example.ricebibackend.service.ChartService;
import com.example.ricebibackend.service.dto.ChartShowDTO;
import com.example.ricebibackend.service.dto.ChartShowSingleDTO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 图表管理实现类
 * @author ricejson
 */
@Service
public class ChartServiceImpl implements ChartService {
    @Resource
    private ChartMapper chartMapper;

    @Override
    public ChartShowDTO getChartListByUploadUserId(ChartShowParam param) {
        // 1. 校验参数
        if (param == null
                || param.getUploadUserId() == null
                || param.getUploadUserId() < 0) {
            throw new ServiceException(ServiceErrorCodeConstants.CHART_SHOW_PARAM_ERROR);
        }
        // 2. 查询数据库获取图表信息(分页获取)
        Long uploadUserId = param.getUploadUserId();
        List<ChartDO> chartDOList = chartMapper.selectList(new Page<>(param.getPageNum(), param.getPageSize())
                , new QueryWrapper<ChartDO>()
                .eq("upload_user_id", uploadUserId));
        // 3. 转化成DTO返回
        List<ChartShowSingleDTO> chartShowSingleDTOList = convertToChartShowDTOList(chartDOList);
        ChartShowDTO chartShowDTO = new ChartShowDTO();
        chartShowDTO.setData(chartShowSingleDTOList);
        chartShowDTO.setTotal(chartMapper.selectCount(new QueryWrapper<ChartDO>()
                .eq("upload_user_id", uploadUserId)));
        return chartShowDTO;
    }

    private List<ChartShowSingleDTO> convertToChartShowDTOList(List<ChartDO> chartDOList) {
        if (chartDOList == null) {
            throw new ServiceException(ServiceErrorCodeConstants.CHART_SHOW_SQL_ERROR);
        }
        List<ChartShowSingleDTO> chartShowSingleDTOList = new ArrayList<>();
        for (ChartDO chartDO : chartDOList) {
            ChartShowSingleDTO dto = new ChartShowSingleDTO();
            dto.setId(chartDO.getId());
            dto.setChartName(chartDO.getChartName());
            dto.setChartType(chartDO.getChartType());
            dto.setGoal(chartDO.getGoal());
            dto.setGenData(chartDO.getGenData());
            dto.setGenResult(chartDO.getGenResult());
            chartShowSingleDTOList.add(dto);
        }
        return chartShowSingleDTOList;
    }


}
